package cn.wizzer.app.web.modules.controllers.platform.bus.equipment;

import cn.wizzer.app.bus.modules.models.equipment.BusEquipment;
import cn.wizzer.app.bus.modules.models.equipment.BusEquipmentCheck;
import cn.wizzer.app.bus.modules.models.equipment.BusEquipmentProcess;
import cn.wizzer.app.bus.modules.models.equipment.BusEquipmentRecord;
import cn.wizzer.app.bus.modules.services.BusEquipmentRecordService;
import cn.wizzer.app.bus.modules.services.BusEquipmentProcessService;
import cn.wizzer.app.bus.modules.services.BusEquipmentService;
import cn.wizzer.app.sys.modules.services.SysDictService;
import cn.wizzer.app.sys.modules.services.SysUnitService;
import cn.wizzer.app.sys.modules.services.SysUserService;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.DateUtil;
import cn.wizzer.app.web.commons.utils.ShiroUtil;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.framework.base.Result;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.integration.json4excel.J4E;
import org.nutz.integration.json4excel.J4EColumn;
import org.nutz.integration.json4excel.J4EConf;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.*;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author tcjinxiu.com
 * @time 2024-04-11 10:19:44
 *
 */
@IocBean
@At("/platform/bus/equipment/record")
public class BusEquipmentRecordController {
private static final Log log = Logs.get();
	@Inject
	BusEquipmentRecordService busEquipmentRecordService;

	@Inject
	BusEquipmentService busEquipmentService;
	@Inject
	BusEquipmentProcessService busEquipmentProcessService;
	@Inject
	private SysDictService sysDictService;
	@Inject
	private SysUnitService sysUnitService;
	@Inject
	private SysUserService sysUserService;
	@Inject
	private ShiroUtil shiroUtil;

	private static final String type="record";
	//public static final int[] EquipmentRecord = {0,1};//流程"ask department chargeLeader finance leadership complete

	@At("/?")
	@Ok("beetl:/platform/bus/equipment/record/index.html")
	@RequiresAuthentication
	public void index(String processName,HttpServletRequest req) {
		//String processCode = sysDictService.getProcessCode(processName);
		req.setAttribute("userId",StringUtil.getPlatformUid());
		req.setAttribute("processName", processName);
		Map processMap =sysDictService.getCodeMap("equipmentProcessCode");
		req.setAttribute("processMap", JSONObject.fromObject(processMap));
		req.setAttribute("processOptions", JSONArray.fromObject(busEquipmentProcessService.listThisProcess(processMap, new int[]{0, 1})));
		req.setAttribute("calculateMap", JSONObject.fromObject(sysDictService.getCodeMap("calculate")));
		req.setAttribute("calculateCycleTypeMap", JSONObject.fromObject(sysDictService.getCodeMap("calculateCycleType")));
	}

	@At
	@Ok("json:full")
	@RequiresAuthentication
	public Object data(@Param("code") String code, @Param("name") String name,@Param("ypbh") String ypbh,
					   @Param("startDate") String startDate,@Param("endDate") String endDate,@Param("lczt") String lczt,@Param("processName") String processName,
					   @Param("pageNumber") int pageNumber,@Param("pageSize") int pageSize
			, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
		try {
			String sql = "select e.code,e.name,e.model,e.company,e.purchaseDate,e.purchasePrice," +
					" ur.username as managerName,ut.name as applyName,urr.username as opName,FROM_UNIXTIME(es.opAt) as opTime, " +
					" es.id,es.lczt,es.jbxxId,es.ypbh,es.startTime,es.endTime,es.startStatus,es.endStatus,es.heat,es.humidity,es.opBy " +
					" from bus_equipment_record es  " +
					" left join bus_equipment e on es.equipmentId=e.id " +
					/*" left join y_jbxx j on es.jbxxId = j.id " +*/
					" left join sys_user ur on ur.id=e.managerBy " +
					" left join sys_unit ut on ut.id = e.applyDept " +
					" left join sys_user urr on urr.id=es.opBy " +
					" where es.delFlag=0 ";
			if(StringUtils.isNotBlank(code)){
				sql+= " and  e.code like '%"+code+"%' ";
			}
			if(StringUtils.isNotBlank(name)){
				sql+= " and  e.name like '%"+name+"%' ";
			}
			if(StringUtils.isNotBlank(lczt)){
				sql+= " and  es.lczt = '"+lczt+"' ";
			}
			if(StringUtils.isNotBlank(ypbh)){
				sql+= " and  es.ypbh like '%"+ypbh+"%' ";
			}
			if(StringUtils.isNotBlank(startDate)){
				sql+= " and  es.startTime >= '"+startDate+"' ";
			}
			if(StringUtils.isNotBlank(endDate)){
				sql+= " and  es.endTime <= '"+endDate+"' ";
			}
			//数据权限
			sql+= StringUtil.dataScopeFilter("es");
			sql="select * from ("+sql+") a";
			if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
				if ("ascending".equalsIgnoreCase(pageOrderBy)) {
					sql+= " order by "+pageOrderName+" asc,opTime desc ";
				} else {
					sql+= " order by "+pageOrderName+" desc,opTime desc ";
				}
			}else{
				sql+= " order by opTime desc ";
			}
			return Result.success().addData(busEquipmentRecordService.listPage(pageNumber, pageSize, Sqls.create(sql)));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error();
		}
	}

	@At
	@Ok("json:full")
	@RequiresAuthentication
	public Object jbxxData(@Param("searchKeyword") String searchKeyword,
					   @Param("pageNumber") int pageNumber,@Param("pageSize") int pageSize) {
		try {
			String sql =" SELECT jbxx.id,jbxx.lzzt,jbxx.lczt, jbxx.ypbh, jbxx.ypmc, jbxx.jylx, jbxx.jyks, " +
					" jbxx.wtdw, jbxx.ggxh, jbxx.scrqpc, jbxx.sb, jbxx.wcqx " +
					" FROM y_jbxx jbxx  " +
					" left join y_jbxx_lcxx lc on lc.jbxxId=jbxx.id and lc.delFlag=0  " +
					"  where 1=1 and jbxx.delflag = 0  and lc.lczt>1 and lc.jyryIds like '%"+StringUtil.getPlatformUid()+"%'"; //只能查询自己检验的
			if (Strings.isNotBlank(searchKeyword)) {
				sql+= " and (jbxx.ypbh like '%"+searchKeyword+"%' or jbxx.ypmc like '%"+searchKeyword+"%') ";
			}
			//只能查询自己登记的数据
			sql+= " order by jbxx.opAt desc ";
			return Result.success().addData(busEquipmentRecordService.listPage(pageNumber, pageSize, Sqls.create(sql)));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error();
		}
	}

	@At
	@Ok("json")
	@RequiresPermissions("equipment.record.add")
	@SLog(tag = "Add", msg = "Add:bus_equipment_record")
	public Object addDo(@Param("..") BusEquipmentRecord record, HttpServletRequest req) {
		try {
			busEquipmentRecordService.insert(record);
			/*if(record.getLczt().equals("1")) {
				BusEquipmentProcess process = new BusEquipmentProcess();
				process.setHeadId(record.getId());
				process.setEquipmentId(record.getEquipmentId());
				process.setLczt(record.getLczt());
				process.setType(type);
				process.setStatus("0");
				process.setOpinion("提交使用记录");
				busEquipmentProcessService.insert(process);
			}*/
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}
	@At("/detail/?")
	@Ok("json")
	@RequiresAuthentication
	public Object detail(String id) {
		BusEquipmentRecord record = busEquipmentRecordService.fetch(id);
		//List listProcess = busEquipmentProcessService.list(Sqls.create("select *,(select username from sys_user where id = es.opBy) as opName,FROM_UNIXTIME(es.opAt) as opTime from  bus_equipment_process es where " +
		//		" equipmentId='"+record.getEquipmentId()+"' and headId='"+record.getId()+"' and type='"+type+"' order by opAt desc"));
		//NutMap map = new NutMap();
		//map.addv("record", record);
		//map.addv("listProcess", listProcess);
		try {
			return Result.success("system.success").addData(record);
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}
	@At
	@Ok("json")
	@RequiresPermissions("equipment.record.edit")
	@SLog(tag = "Edit", msg = "Edit:bus_equipment_record")
	public Object editDo(@Param("..") BusEquipmentRecord record, HttpServletRequest req) {
		try {
			busEquipmentRecordService.update(record);
			/*if(record.getLczt().equals("1")) {
				//BusEquipment equipment = busEquipmentService.fetch(servicing.getEquipmentId());
				//equipment.setStatus("5");
				BusEquipmentProcess process = new BusEquipmentProcess();
				process.setHeadId(record.getId());
				process.setEquipmentId(record.getEquipmentId());
				process.setLczt(record.getLczt());
				process.setType(type);
				process.setStatus("0");
				process.setOpinion("提交使用记录");
				Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
					public void run() {
						busEquipmentRecordService.updateIgnoreNull(record);
						busEquipmentProcessService.execute(Sqls.create("update bus_equipment_process set delflag=1 where lczt>="+record.getLczt()+" and headId='"+record.getId()+"' and type='"+type+"' "));
						busEquipmentProcessService.insert(process);
					}
				});
			}else{
				busEquipmentRecordService.updateIgnoreNull(record);
			}*/
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}
	@At("/subDo/?")
	@Ok("json")
	@RequiresPermissions("equipment.record.edit")
	@SLog(tag = "subDo", msg = "subDo:bus_equipment_record")
	public Object subDo(String id) {
		try {
			BusEquipmentRecord record = busEquipmentRecordService.fetch(id);
			record.setLczt("1");
			busEquipmentRecordService.update(record);
			/*BusEquipmentProcess process = new BusEquipmentProcess();
			process.setHeadId(record.getId());
			process.setEquipmentId(record.getEquipmentId());
			process.setLczt(record.getLczt());
			process.setType(type);
			process.setStatus("0");
			process.setOpinion("提交使用记录");
			Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
				public void run() {
					busEquipmentRecordService.updateIgnoreNull(record);
					busEquipmentProcessService.execute(Sqls.create("update bus_equipment_process set delflag=1 where lczt>=" + record.getLczt() + " and headId='" + record.getId() + "' and type='"+type+"' "));
					busEquipmentProcessService.insert(process);
				}
			});*/
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@At
	@Ok("json")
	@RequiresAuthentication
	@SLog(tag = "processDo", msg = "processDo:bus_equipment_record")
	public Object processDo(@Param("..") BusEquipmentRecord record,@Param("..") BusEquipmentProcess process,
							@Param("processCode") String processCode,
							HttpServletRequest req) {
		try {
			record.setLczt("");
			process.setHeadId(record.getId());
			process.setEquipmentId(record.getEquipmentId());
			process.setLczt(record.getLczt());
			process.setType(type);
			Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
				public void run() {
					//busEquipmentService.updateIgnoreNull(equipment);
					//先清除流程
					busEquipmentProcessService.execute(Sqls.create("update bus_equipment_process set delflag=1 where lczt>="+processCode+" and headId='"+record.getId()+"' and type='"+type+"' "));
					busEquipmentRecordService.updateIgnoreNull(record);
					busEquipmentProcessService.insert(process);
				}
			});
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@At({"/delete","/delete/?"})
	@Ok("json")
	@RequiresPermissions("equipment.record.delete")
	@SLog(tag = "Delete", msg = "Delete:bus_equipment_record")
	public Object delete(String id,@Param("ids") String[] ids, HttpServletRequest req) {
		try {
			if(ids!=null&&ids.length>0){
				busEquipmentRecordService.vDelete(ids);
			}else{
				busEquipmentRecordService.vDelete(id);
			}
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}
	@At
	@Ok("void")
	public void export(@Param("code") String code, @Param("name") String name,@Param("ypbh") String ypbh,
					   @Param("lczt") String lczt,@Param("startDate") String startDate,@Param("endDate") String endDate
			,@Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy, HttpServletResponse response) {
		try {
			String sql = "select e.code,e.name,e.model,e.company,e.purchaseDate,e.purchasePrice," +
					" ur.username as managerName,ut.name as applyName,urr.username as opName,FROM_UNIXTIME(es.opAt) as opTime, " +
					" es.id,es.lczt,es.jbxxId,es.ypbh,es.startTime,es.endTime,es.startStatus,es.endStatus,es.heat,es.humidity,es.opBy " +
					" from bus_equipment_record es  " +
					" left join bus_equipment e on es.equipmentId=e.id " +
					/*" left join y_jbxx j on es.jbxxId = j.id " +*/
					" left join sys_user ur on ur.id=e.managerBy " +
					" left join sys_unit ut on ut.id = e.applyDept " +
					" left join sys_user urr on urr.id=es.opBy " +
					" where es.delFlag=0 ";
			if(StringUtils.isNotBlank(code)){
				sql+= " and  e.code like '%"+code+"%' ";
			}
			if(StringUtils.isNotBlank(name)){
				sql+= " and  e.name like '%"+name+"%' ";
			}
			if(StringUtils.isNotBlank(lczt)){
				sql+= " and  es.lczt = '"+lczt+"' ";
			}
			if(StringUtils.isNotBlank(ypbh)){
				sql+= " and  es.ypbh like '%"+ypbh+"%' ";
			}
			if(StringUtils.isNotBlank(startDate)){
				sql+= " and  es.startTime >= '"+startDate+"' ";
			}
			if(StringUtils.isNotBlank(endDate)){
				sql+= " and  es.endTime <= '"+endDate+"' ";
			}
			//数据权限
			sql+= StringUtil.dataScopeFilter("es");
			sql="select * from ("+sql+") a";
			if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
				if ("ascending".equalsIgnoreCase(pageOrderBy)) {
					sql+= " order by "+pageOrderName+" asc,opTime desc ";
				} else {
					sql+= " order by "+pageOrderName+" desc,opTime desc ";
				}
			}else{
				sql+= " order by opTime desc ";
			}
			List<BusEquipmentRecord> listObj = busEquipmentRecordService.listEntity(Sqls.create(sql));

			Map processMap =sysDictService.getCodeMap("equipmentProcessCode");
			listObj.stream().map(obj -> {
				obj.setLczt(processMap.get(obj.getLczt())==null?"":processMap.get(obj.getLczt()).toString());
				return obj;
			}).collect(Collectors.toList());

			J4EConf j4eConf = J4EConf.from(BusEquipmentRecord.class);
			List<J4EColumn> jcols = j4eConf.getColumns();
			for (J4EColumn j4eColumn : jcols) {
				if ("opBy".equals(j4eColumn.getFieldName()) || "opAt".equals(j4eColumn.getFieldName()) || "delFlag".equals(j4eColumn.getFieldName())) {
					j4eColumn.setIgnore(true);
				}
			}
			j4eConf.setSheetName(j4eConf.getSheetName()+ DateUtil.getDate());
			OutputStream out = response.getOutputStream();
			response.setHeader("content-type", "application/shlnd.ms-excel;charset=utf-8");
			response.setHeader("content-disposition", "attachment; filename=" + new String(j4eConf.getSheetName().getBytes(), "ISO-8859-1") + ".xls");
			J4E.toExcel(out, listObj, j4eConf);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

}
